package com.changgou.seckill.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.service.SeckillOrderService;
import entity.RedisConfig;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = {"${mq.pay.queue.seckillorder}"})
public class OrderMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillOrderService seckillOrderService;

    /****
     * 监听消息
     * @param msg
     */
    @RabbitHandler
    public void consumeMessage(@Payload String msg) {
        RedisConfig.convertRedisTemplate(redisTemplate);

        Map<String, String> msgMap = JSON.parseObject(msg, Map.class);

        //通信成功
        if (msgMap.get("return_code").equalsIgnoreCase("success")) {
            //获取附加信息
            Map<String, String> attachMap = JSON.parseObject(msgMap.get("attach"), Map.class);
            String username = attachMap.get("username");
            if (username == null) {
                return;
            }
            //支付成功
            if (msgMap.get("result_code").equalsIgnoreCase("success")) {
                //修改订单状态
                seckillOrderService.updateStatus(username, msgMap.get("transaction_id"));
            } else {
                //支付失败，删除订单
                seckillOrderService.deleteOrder(username);
            }
        }
    }
}
